package com.yk.faceapplication.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.allinpay.xed.R;
import com.android.volley.VolleyError;
import com.sensetime.stlivenesslibrary.util.Constants;
import com.yk.faceapplication.callback.LoanPurposeCallback;
import com.yk.faceapplication.callback.RequestCallback;
import com.yk.faceapplication.callback.TakePicCallback;
import com.yk.faceapplication.callback.UploadCallback;
import com.yk.faceapplication.entity.BankInfo;
import com.yk.faceapplication.entity.Card;
import com.yk.faceapplication.entity.Member;
import com.yk.faceapplication.entity.Purpose;
import com.yk.faceapplication.entity.StudyInfo;
import com.yk.faceapplication.http.RequestUrl;
import com.yk.faceapplication.util.ActivityUtil;
import com.yk.faceapplication.util.ImageUtil;
import com.yk.faceapplication.util.InputFilterX;
import com.yk.faceapplication.util.LogDebugger;
import com.yk.faceapplication.util.RequestUtil;
import com.yk.faceapplication.util.UploadUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yk.faceapplication.util.ActivityUtil.FOLDER_TEMP_FILE_IMG;

//import com.sensetime.stlivenesslibrary.util.Constants;

/**
 * Created by yk_2018/1/16_12:24
 */

public class MemberInfoActivity extends BaseActivity {
    private ImageView cardFIV, cardZIV, avatarIV;
    private final int REQUEST_IMG_Z = 1;
    private final int REQUEST_IMG_F = 2;
    private final int REQUEST_PHOTO_Z = 3;
    private final int REQUEST_PHOTO_F = 4;

    private final int UPDATA_CARD_Z = 1000;
    private final int UPDATA_CARD_F = 1001;
    private final int FACE_REQUEST = 1002;
    private final int UPDATA_FACE = 1003;

    private String cardZId, cardFId, faceId, resultId;

    private Uri cardFrontUri;

    private RelativeLayout bankLayout, bankTypeLayout, studyLayout, workLayout;
    private ImageView bankRightIV, bankTypeRightIV, studyRightIV, workRightIV;
    private TextView bankTV;
    private TextView bankTypeTV;
    private TextView studyTV;
    private TextView workTV;

    private EditText nameET, cardET, bankCardET, phoneET;

    private Button saveTV;

    //    private int currentBankPosition = -1;
    private String currentBankCode = null;
    private String currentBankTypeCode;
    private int currentEducationPosition = -1;
    private String currentWorkCode;

    private Dialog uploadDialog;
    private Dialog loadingDialog;
    private Dialog workDialog;

    private Dialog takePicDialog;

    private void initMemberInfo() {
        Member member = mApplication.getMember();
        if (member.getPeople() != null && member.getCards() != null && !member.getCards().isEmpty()) {
            saveTV.setVisibility(View.GONE);
        }
        if (member.getPeople() != null) {
            studyLayout.setEnabled(false);
            workLayout.setEnabled(false);
            nameET.setText(member.getPeople().getName());
            cardET.setText(member.getPeople().getIdCardNo());
            ImageUtil.displayImage(this, member.getPeople().getIdCardBack(), cardFIV);
            ImageUtil.displayImage(this, member.getPeople().getIdCardFront(), cardZIV);
            ImageUtil.displayImage(this, member.getPeople().getFacePhoto(), avatarIV);
            cardFIV.setEnabled(false);
            cardZIV.setEnabled(false);
            avatarIV.setEnabled(false);
            nameET.setEnabled(false);
            cardET.setEnabled(false);
            cardZId = member.getPeople().getIdCardFront();
            cardFId = member.getPeople().getIdCardBack();
            faceId = member.getPeople().getFacePhoto();
            if (mApplication.getMember().getPeople().getCareer() != null && mApplication.getWorks() != null) {
                for (Purpose type : mApplication.getWorks()) {
                    for (Purpose work : type.getChildren()) {
                        if (work.getCode().equals(mApplication.getMember().getPeople().getCareer())) {
                            workTV.setText(work.getValue());
                            break;
                        }
                    }
                }
            }
            if (mApplication.getMember().getPeople().getEducation() != null && mApplication.getStudyInfos() != null) {
                for (StudyInfo study : mApplication.getStudyInfos()) {
                    if (study.getCode().equals(mApplication.getMember().getPeople().getEducation())) {
                        studyTV.setText(study.getValue());
                        break;
                    }
                }
            }
        }
        if (member.getCards() != null && !member.getCards().isEmpty()) {
            Card card = member.getCards().get(0);
            bankCardET.setText(card.getCreditCardNo());
            phoneET.setText(card.getMobile());
            bankTV.setText(card.getBankName());
            if (card.getType() == 0) {
                bankTypeTV.setText("借记卡");
            } else {
                bankTypeTV.setText("信用卡");
            }
            //            bankTypeTV.setText(card.getBankName());

            bankCardET.setEnabled(false);
            phoneET.setEnabled(false);

            bankLayout.setEnabled(false);
            bankTypeLayout.setEnabled(false);

        }
    }

    private boolean saveMemberInfo = false;

    private void saveInfo() {
        loadingDialog = ActivityUtil.createLoadingDialog(this, "保存中,请稍候~");
        loadingDialog.show();
        Map<String, String> form = new HashMap<String, String>();
        form.put("encryptionId", resultId);//加密数据ID
        form.put("facePhoto", faceId);
        form.put("idCardFront", cardZId);
        form.put("idCardBack", cardFId);

        form.put("name", nameET.getText().toString().trim());
        form.put("idCardNo", cardET.getText().toString().trim());
        form.put("creditCardNo", bankCardET.getText().toString().trim());

        form.put("bankCode", currentBankCode);//发卡行CODE
        form.put("idType", currentBankTypeCode);//银行卡类型
        form.put("bankName", bankTV.getText().toString());

        form.put("telMobile", phoneET.getText().toString().trim());
        form.put("education", mApplication.getStudyInfos().get(currentEducationPosition).getCode());
        form.put("career", currentWorkCode);

        LogDebugger.info(form.toString());
        LogDebugger.info(RequestUrl.SAVE_PEOPLE + "token=" + mToken);

        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                //                                Toast.makeText(mApplication, "用户保存成功", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                //                finishAct();
                loadingDialog.dismiss();
                saveMemberInfo = true;
                saveCard();
            }

            @Override
            public void fail(VolleyError volleyError) {
                loadingDialog.dismiss();
                Toast.makeText(mApplication, "保存个人信息失败", Toast.LENGTH_SHORT).show();
            }
        };
        RequestUtil.request(this, RequestUrl.SAVE_PEOPLE + "token=" + mToken, callback, form);
    }

    private void saveCard() {
        loadingDialog = ActivityUtil.createLoadingDialog(this, "保存中,请稍候~");
        loadingDialog.show();


        Map<String, String> form = new HashMap<String, String>();

        form.put("name", nameET.getText().toString().trim());
        form.put("idCardNo", cardET.getText().toString().trim());
        form.put("creditCardNo", bankCardET.getText().toString().trim());

        form.put("bankCode", currentBankCode);//发卡行CODE
        form.put("idType", currentBankTypeCode);//银行卡类型
        form.put("bankName", bankTV.getText().toString());

        form.put("telMobile", phoneET.getText().toString().trim());


        RequestCallback callback = new RequestCallback() {
            @Override
            public void success(JSONObject jsonObject) {
                loadingDialog.dismiss();
                Toast.makeText(mApplication, "保存成功", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                finishAct();
            }

            @Override
            public void fail(VolleyError volleyError) {
                loadingDialog.dismiss();
//                Toast.makeText(mApplication, "绑卡失败", Toast.LENGTH_SHORT).show();
            }
        };
        RequestUtil.request(this, RequestUrl.SAVE_CARD + "token=" + mToken, callback, form);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.save_tv:

                if (mApplication.getMember().getPeople() == null && !saveMemberInfo) {
                    if (faceId == null || resultId == null || cardFId == null || cardZId == null || ActivityUtil.editIsNull(nameET) || ActivityUtil.editIsNull(cardET) || ActivityUtil.editIsNull(bankCardET) || ActivityUtil.editIsNull(phoneET) || ActivityUtil.textIsNull(bankTV) || ActivityUtil.textIsNull(bankTypeTV) || ActivityUtil.textIsNull(studyTV) || ActivityUtil.textIsNull(workTV)) {
                        Toast.makeText(mApplication, "请输入完整信息后保存", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(bankCardET.getText().toString().trim().length()<13){
                        Toast.makeText(mApplication, "银行卡号位数不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    saveInfo();
                } else {
                    if (ActivityUtil.editIsNull(nameET) || ActivityUtil.editIsNull(cardET) || ActivityUtil.editIsNull(bankCardET) || ActivityUtil.editIsNull(phoneET) || ActivityUtil.textIsNull(bankTV) || ActivityUtil.textIsNull(bankTypeTV)) {
                        Toast.makeText(mApplication, "请输入完整信息后保存", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if(bankCardET.getText().toString().trim().length()<13){
                        Toast.makeText(mApplication, "银行卡号位数不正确", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    saveCard();
                }
                break;
            case R.id.bank_layout:
                if(mApplication.getBanks() == null){
                    Toast.makeText(MemberInfoActivity.this,"网络异常",Toast.LENGTH_LONG).show();
                    return;
                }
                // 点击控件后显示popup窗口
                List<String> dataList = new ArrayList<>();
                for (BankInfo bank : mApplication.getBanks()) {
                    dataList.add(bank.getBankName());
                }
                initSelectPopup(dataList, bankTV);
                // 使用isShowing()检查popup窗口是否在显示状态
                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                    typeSelectPopup.showAsDropDown(bankRightIV, 0, 10);
                }
                break;
            case R.id.bank_type_layout:
                // 点击控件后显示popup窗口
                dataList = new ArrayList<>();
                dataList.add("借记卡");
                dataList.add("信用卡");
                //                for (StudyInfo bankType : mApplication.getBankTypes()) {
                //                    dataList.add(bankType.getValue());
                //                }
                initSelectPopup(dataList, bankTypeTV);
                // 使用isShowing()检查popup窗口是否在显示状态
                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                    typeSelectPopup.showAsDropDown(bankTypeRightIV, 0, 10);
                }
                break;
            case R.id.study_layout:
                // 点击控件后显示popup窗口
                if(mApplication.getStudyInfos() == null){
                    Toast.makeText(MemberInfoActivity.this,"网络异常",Toast.LENGTH_LONG).show();
                    return;
                }
                if (mApplication.getStudyInfos() != null) {
                    dataList = new ArrayList<>();
                    for (StudyInfo studyInfo : mApplication.getStudyInfos()) {
                        dataList.add(studyInfo.getValue());
                    }
                    initSelectPopup(dataList, studyTV);
                    // 使用isShowing()检查popup窗口是否在显示状态
                    if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                        typeSelectPopup.showAsDropDown(studyRightIV, 0, -500);
                    }
                }
                break;
            case R.id.work_layout:
                //                // 点击控件后显示popup窗口
                //                dataList = new ArrayList<>();
                //                for (WorkInfo workInfo : mApplication.getWorks()) {
                //                    dataList.add(workInfo.getValue());
                //                }
                //                initSelectPopup(dataList, workTV);
                //                // 使用isShowing()检查popup窗口是否在显示状态
                //                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                //                    typeSelectPopup.showAsDropDown(workRightIV, 0, -600);
                //                }
                if (workDialog != null){
                    workDialog.show();
                }else{
                    Toast.makeText(MemberInfoActivity.this,"网络异常",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.card_z_icon:
                takePicType = "z";
                takePicDialog.show();
                //                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //                startActivityForResult(intent, REQUEST_IMG_Z);
                break;
            case R.id.card_f_icon:
                takePicType = "f";
                takePicDialog.show();
                //                intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //                startActivityForResult(intent, REQUEST_IMG_F);
                break;
            case R.id.avatar_img:
                openLivenessActivity(this);
                break;
        }
    }

    /**
     * popup窗口里的ListView
     */
    private ListView mTypeLv;

    /**
     * popup窗口
     */
    private PopupWindow typeSelectPopup;

    /**
     * 模拟的假数据
     */
    private List<String> testData;

    /**
     * 数据适配器
     */
    private ArrayAdapter<String> testDataAdapter;

    /**
     * 初始化popup窗口
     */
    private void initSelectPopup(final List<String> dataList, final TextView tv) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
        mTypeLv = new ListView(this);
        //        TestData();
        // 设置适配器
        testDataAdapter = new ArrayAdapter<String>(this, R.layout.popup_text_item, dataList);
        mTypeLv.setAdapter(testDataAdapter);

        // 设置ListView点击事件监听
        mTypeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 在这里获取item数据
                if (tv.getId() == R.id.bank_tv) {
                    //                    currentBankPosition = position;
                    currentBankCode = mApplication.getBanks().get(position).getBankCode();
                } else if (tv.getId() == R.id.study_tv) {
                    currentEducationPosition = position;
                } else if (tv.getId() == R.id.bank_type_tv) {
                    if (dataList.get(position).equals("借记卡")) {
                        currentBankTypeCode = "0";
                    } else {
                        currentBankTypeCode = "1";
                    }
                }


                String value = dataList.get(position);
                // 把选择的数据展示对应的TextView上
                tv.setText(value);
                // 选择完后关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
        typeSelectPopup = new PopupWindow(mTypeLv, 300, ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 取得popup窗口的背景图片
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_filter_down);
        typeSelectPopup.setBackgroundDrawable(drawable);
        typeSelectPopup.setFocusable(true);
        typeSelectPopup.setOutsideTouchable(true);
        typeSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
    }

    @Override
    protected void onHandleMessage(Message msg) {
        super.onHandleMessage(msg);
        switch (msg.what) {
            case UPDATA_CARD_Z:
                ImageUtil.displayImage(mApplication, cardZId, cardZIV);
                //                LogDebugger.info(cardFrontUri.getHost());
                //                LogDebugger.info(cardFrontUri.getPath());
                //                LogDebugger.info(cardFrontUri.getEncodedPath());

                //                ImageUtil.displayImage(mApplication, cardFrontUri, cardZIV);
                //                cardZIV.setImageUri(Uri.fromFile(new File("/sdcard/test.jpg")));
                break;
            case UPDATA_CARD_F:
                ImageUtil.displayImage(mApplication, cardFId, cardFIV);
                break;
            case UPDATA_FACE:
                ImageUtil.displayImage(mApplication, faceId, avatarIV);
                break;

        }
    }

    public void openLivenessActivity(Activity activity) {
        LogDebugger.info("openLivenessActivity");
        try {
            Bundle bundle = new Bundle();
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append(Constants.BLINK + " ");
            sBuilder.append(Constants.MOUTH + " ");
            sBuilder.append(Constants.NOD + " ");
            sBuilder.append(Constants.YAW + " ");
            /**
             * OUTPUT_TYPE 配置, 传入的outputType类型为singleImg （单图），multiImg （多图），video（低质量视频），fullvideo（高质量视频）
             */
            bundle.putString(com.sensetime.stlivenesslibrary.ui.LivenessActivity.OUTTYPE, Constants.MULTIIMG);
            /**
             * EXTRA_MOTION_SEQUENCE 动作检测序列配置，支持四种检测动作， BLINK(眨眼), MOUTH（张嘴）, NOD（点头）, YAW（摇头）, 各个动作以空格隔开。 推荐第一个动作为BLINK。
             * 默认配置为"BLINK MOUTH NOD YAW"
             */
            bundle.putString(com.sensetime.stlivenesslibrary.ui.LivenessActivity.EXTRA_MOTION_SEQUENCE, sBuilder.toString());
            /**
             * SOUND_NOTICE 配置, 传入的soundNotice为boolean值，true为打开, false为关闭。
             */
            bundle.putBoolean(com.sensetime.stlivenesslibrary.ui.LivenessActivity.SOUND_NOTICE, true);
            /**
             * COMPLEXITY 配置, 传入的complexity类型为normal,支持四种难度，easy, normal, hard, hell.
             */
            bundle.putString(com.sensetime.stlivenesslibrary.ui.LivenessActivity.COMPLEXITY, Constants.EASY);

            Intent intent = new Intent();
            intent.putExtras(bundle);
            intent.setClass(activity, com.sensetime.stlivenesslibrary.ui.LivenessActivity.class);
            intent.putExtras(bundle);
            activity.startActivityForResult(intent, FACE_REQUEST);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PHOTO_Z:
                    if (resultCode == RESULT_OK) {

                        Bitmap bm = (Bitmap) data.getExtras().get("data");
                        ActivityUtil.compressImageToFile(bm, "card_z.jpg");
                        uploadDialog = ActivityUtil.createLoadingDialog(this, "上传中,请稍候~");
                        uploadDialog.show();
                        final UploadCallback takePhotoCallback = new UploadCallback() {
                            @Override
                            public void success(String str) {
                                LogDebugger.info(str);
                                uploadDialog.dismiss();
                                uploadDialog = null;
                                try {
                                    String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                    cardZId = fileId;
                                    sendMessage(UPDATA_CARD_Z);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void fail(VolleyError volleyError) {
                                uploadDialog.dismiss();
                                uploadDialog = null;
                            }
                        };
                        Runnable takePhotoTask = new Runnable() {
                            @Override
                            public void run() {
                                // 在这里进行 http request.网络请求相关操作
                                File file = new File(FOLDER_TEMP_FILE_IMG, "card_z.jpg");
                                try {
                                    UploadUtil.uploadForm(null, "file", file, null, mToken, takePhotoCallback);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        new Thread(takePhotoTask).start();
                    }
                    break;
                case REQUEST_PHOTO_F:
                    if (resultCode == RESULT_OK) {
                        Bitmap bm = (Bitmap) data.getExtras().get("data");
                        ActivityUtil.compressImageToFile(bm, "card_f.jpg");
                        uploadDialog = ActivityUtil.createLoadingDialog(this, "上传中,请稍候~");
                        uploadDialog.show();
                        final UploadCallback takePhotoCallback = new UploadCallback() {
                            @Override
                            public void success(String str) {
                                LogDebugger.info(str);
                                uploadDialog.dismiss();
                                uploadDialog = null;
                                try {
                                    String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                    cardFId = fileId;
                                    sendMessage(UPDATA_CARD_F);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void fail(VolleyError volleyError) {
                                uploadDialog.dismiss();
                                uploadDialog = null;
                            }
                        };
                        Runnable takePhotoTask = new Runnable() {
                            @Override
                            public void run() {
                                // 在这里进行 http request.网络请求相关操作
                                File file = new File(FOLDER_TEMP_FILE_IMG, "card_f.jpg");
                                try {
                                    UploadUtil.uploadForm(null, "file", file, null, mToken, takePhotoCallback);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        };
                        new Thread(takePhotoTask).start();
                    }
                    break;
                case REQUEST_IMG_Z:
                    uploadDialog = ActivityUtil.createLoadingDialog(this, "上传中,请稍候~");
                    uploadDialog.show();
                    Uri uri = data.getData();
                    cardFrontUri = data.getData();
                    ContentResolver cr = this.getContentResolver();
                    Cursor c = cr.query(uri, null, null, null, null);
                    c.moveToFirst();
                    //这是获取的图片保存在sdcard中的位置
                    String srcPath = c.getString(c.getColumnIndex("_data"));
                    LogDebugger.info(srcPath);
                    ActivityUtil.compressImageToFile(srcPath, "card_z.jpg");
                    final UploadCallback callback = new UploadCallback() {
                        @Override
                        public void success(String str) {
                            LogDebugger.info(str);
                            uploadDialog.dismiss();
                            uploadDialog = null;
                            try {
                                String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                cardZId = fileId;
                                sendMessage(UPDATA_CARD_Z);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void fail(VolleyError volleyError) {
                            uploadDialog.dismiss();
                            uploadDialog = null;
                        }
                    };
                    Runnable networkTask = new Runnable() {
                        @Override
                        public void run() {
                            // 在这里进行 http request.网络请求相关操作
                            File file = new File(FOLDER_TEMP_FILE_IMG, "card_z.jpg");
                            try {
                                UploadUtil.uploadForm(null, "file", file, null, mToken, callback);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    new Thread(networkTask).start();

                    break;
                case REQUEST_IMG_F:
                    LogDebugger.info("uploading...");
                    uploadDialog = ActivityUtil.createLoadingDialog(this, "上传中,请稍候~");
                    uploadDialog.show();
                    Uri uri2 = data.getData();
                    ContentResolver cr2 = this.getContentResolver();
                    Cursor c2 = cr2.query(uri2, null, null, null, null);
                    c2.moveToFirst();
                    //这是获取的图片保存在sdcard中的位置
                    String srcPath2 = c2.getString(c2.getColumnIndex("_data"));
                    //                    Toast.makeText(mApplication, srcPath2, Toast.LENGTH_SHORT).show();
                    LogDebugger.info(srcPath2);
                    ActivityUtil.compressImageToFile(srcPath2, "card_f.jpg");
                    final UploadCallback callback2 = new UploadCallback() {
                        @Override
                        public void success(String str) {
                            LogDebugger.info(str);
                            uploadDialog.dismiss();
                            uploadDialog = null;
                            try {
                                String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                cardFId = fileId;
                                sendMessage(UPDATA_CARD_F);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void fail(VolleyError volleyError) {
                            uploadDialog.dismiss();
                            uploadDialog = null;
                        }
                    };
                    networkTask = new Runnable() {
                        @Override
                        public void run() {
                            // 在这里进行 http request.网络请求相关操作
                            File file = new File(FOLDER_TEMP_FILE_IMG, "card_f.jpg");
                            try {
                                UploadUtil.uploadForm(null, "file", file, null, mToken, callback2);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    new Thread(networkTask).start();


                    break;
                case FACE_REQUEST:
                    byte[] img = data.getByteArrayExtra("image0");
                    Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);


                    FileOutputStream b = null;
                    File file = new File("/sdcard/Face/");
                    file.mkdirs();// 创建文件夹
                    final String fileName = "/sdcard/Face/temp.jpg";

                    try {
                        b = new FileOutputStream(fileName);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            b.flush();
                            b.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }


                    final UploadCallback callback3 = new UploadCallback() {
                        @Override
                        public void success(String str) {
                            LogDebugger.info(str);
                            try {
                                String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                faceId = fileId;
                                sendMessage(UPDATA_FACE);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void fail(VolleyError volleyError) {

                        }
                    };
                    Runnable networkTask3 = new Runnable() {
                        @Override
                        public void run() {
                            // 在这里进行 http request.网络请求相关操作
                            File file = new File(fileName);
                            try {
                                //                                UploadUtil.uploadForm(null, "file", file, null, mToken, callback3);
                                UploadUtil.uploadForm(null, "file", file, null, mToken, callback3);


                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    new Thread(networkTask3).start();


                    final UploadCallback callback4 = new UploadCallback() {
                        @Override
                        public void success(String str) {
                            LogDebugger.info(str);
                            try {
                                String fileId = new org.json.JSONObject(str).getJSONObject("data").getString("file");
                                resultId = fileId;
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void fail(VolleyError volleyError) {

                        }
                    };
                    Runnable networkTask4 = new Runnable() {
                        @Override
                        public void run() {
                            // 在这里进行 http request.网络请求相关操作
                            final File resultFile = new File("/sdcard/liveness/livenessResult");
                            try {
                                UploadUtil.uploadDataForm(null, "file", resultFile, null, mToken, callback4);


                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    new Thread(networkTask4).start();
                    break;
                default:
                    break;
            }
        }
        //      n =1;
    }

    public boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ((!verifyCameraPermissions() || !verifyStoragePermissions() || !verifyPositionPermissions()) && mApplication.getMember().getPeople() == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("请打开相机、读写和位置权限,否则此功能将无法使用");
            builder.setCancelable(false);
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(getAppDetailSettingIntent());
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
        //        verifyStoragePermissions(this);

        //        if ((!cameraIsCanUse() || !verifyStoragePermissions(this)) && mApplication.getMember().getPeople() == null) {
        //            AlertDialog.Builder builder = new AlertDialog.Builder(this);
        //            builder.setTitle("提示");
        //            builder.setMessage("请检查相机和读写权限");
        //            builder.setCancelable(false);
        //            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
        //                @Override
        //                public void onClick(DialogInterface dialog, int which) {
        //                    startActivity(getAppDetailSettingIntent());
        //                    dialog.dismiss();
        //                }
        //            });
        //            builder.create().show();
        //        }

    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"};


    public boolean verifyStoragePermissions() {

        try {
            //检测是否有写的权限
            int permission = ActivityCompat.checkSelfPermission(this, "android.permission.WRITE_EXTERNAL_STORAGE");
            if (permission != PackageManager.PERMISSION_GRANTED) {
                // 没有写的权限，去申请写的权限，会弹出对话框
                //                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    public boolean verifyPositionPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    public boolean verifyCameraPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }



    /**
     * 获取应用详情页面intent
     *
     * @return
     */
    private Intent getAppDetailSettingIntent() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        return localIntent;
    }

    private String takePicType;

    private TakePicCallback takePicCallback = new TakePicCallback() {
        @Override
        public void takePhoto() {
            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //系统常量， 启动相机的关键
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                openCameraIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
            }
            if (takePicType.equals("z")) {
                startActivityForResult(openCameraIntent, REQUEST_PHOTO_Z); // 参数常量为自定义的request code, 在取返回结果时有用
            } else {
                startActivityForResult(openCameraIntent, REQUEST_PHOTO_F); // 参数常量为自定义的request code, 在取返回结果时有用
            }

            takePicDialog.dismiss();
        }

        @Override
        public void takeImg() {
            if (takePicType.equals("z")) {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_IMG_Z);
            } else {
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, REQUEST_IMG_F);
            }
            takePicDialog.dismiss();
        }

        @Override
        public void cancel() {
            takePicDialog.dismiss();
        }
    };



    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
        setTitle("个人信息");

        takePicDialog = ActivityUtil.createTakePicDialog(this, takePicCallback);
        LoanPurposeCallback callback = new LoanPurposeCallback() {
            @Override
            public void success(Purpose option) {
                currentWorkCode = option.getCode();
                workTV.setText(option.getValue());
                workDialog.dismiss();
            }

            @Override
            public void cancel() {
                workDialog.dismiss();
            }
        };
        if (mApplication.getWorks() != null) {
            workDialog = ActivityUtil.createLoanPurposeDialog(MemberInfoActivity.this, mApplication.getWorks(), callback);
        }
        nameET = (EditText) findViewById(R.id.name_et);
        cardET = (EditText) findViewById(R.id.card_et);

        cardET.setFilters(new InputFilter[] { new InputFilterX() });


        bankCardET = (EditText) findViewById(R.id.bank_card_et);
        phoneET = (EditText) findViewById(R.id.phone_et);

        saveTV = (Button) findViewById(R.id.save_tv);
        saveTV.setOnClickListener(this);

        cardZIV = (ImageView) findViewById(R.id.card_z_icon);
        cardFIV = (ImageView) findViewById(R.id.card_f_icon);
        cardZIV.setOnClickListener(this);
        cardFIV.setOnClickListener(this);
        avatarIV = (ImageView) findViewById(R.id.avatar_img);
        avatarIV.setOnClickListener(this);
        bankLayout = (RelativeLayout) findViewById(R.id.bank_layout);
        bankLayout.setOnClickListener(this);

        bankTypeLayout = (RelativeLayout) findViewById(R.id.bank_type_layout);
        bankTypeLayout.setOnClickListener(this);

        studyLayout = (RelativeLayout) findViewById(R.id.study_layout);
        studyLayout.setOnClickListener(this);

        workLayout = (RelativeLayout) findViewById(R.id.work_layout);
        workLayout.setOnClickListener(this);

        bankRightIV = (ImageView) findViewById(R.id.bank_right_iv);
        bankTV = (TextView) findViewById(R.id.bank_tv);
        bankTypeTV = (TextView) findViewById(R.id.bank_type_tv);
        studyTV = (TextView) findViewById(R.id.study_tv);
        workTV = (TextView) findViewById(R.id.work_tv);

        bankTypeRightIV = (ImageView) findViewById(R.id.bank_type_right_iv);
        studyRightIV = (ImageView) findViewById(R.id.study_right_iv);
        workRightIV = (ImageView) findViewById(R.id.work_right_iv);

        initMemberInfo();

        //        uploadDialog = ActivityUtil.createLoadingDialog(this, "上传中,请稍候~");


    }
//13771887301
    /**
     *
     * @Description: 上传方法
     *
     * @param audioPath
     *            上传音频文件地址 例：sdcard/image/a.amr
     *
     * @param text
     *            上传文本的值
     *
     * @param imageUrlList
     *            图片地址的集合 例：sdcard/image/a.jpg, sdcard/image/b.jpg
     *
     * @return void
     */

    //    private synchronized void postMethod(String text, String audioPath,
    //                                         List<String> imageUrlList) {
    //        try {
    //            String[] filePath = new String[imageUrlList.size()];
    //            int size = imageUrlList.size();
    //            for (int i = 0; i < size; i++) {
    //                filePath[i] = imageUrlList.get(i);
    //            }
    //            // 链接超时，请求超时设置
    //            BasicHttpParams httpParams = new BasicHttpParams();
    //            HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
    //            HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);
    //
    //            // 请求参数设置
    //            HttpClient client = new DefaultHttpClient(httpParams);
    //            HttpPost post = new HttpPost(
    //                    "http://service.ireadhome.com/api/Upload/Image");
    //            MultipartEntity entity = new MultipartEntity();
    //            // 上传 文本， 转换编码为utf-8 其中"text" 为字段名，
    //            // 后边new StringBody(text,
    //            // Charset.forName(CHARSET))为参数值，其实就是正常的值转换成utf-8的编码格式
    //            entity.addPart("text",
    //                    new StringBody(text, Charset.forName("UTF-8")));
    //            // 上传多个文本可以在此处添加上边代码，修改字段和值即可
    //
    //            // 上传音频文件
    //            entity.addPart("audio",
    //                    new FileBody(new File(audioPath), "audio/*"));
    //            // 上传图片
    //            for (String p : filePath) {
    //                entity.addPart("fileimg", new FileBody(new File(p), "image/*"));
    //            }
    //            post.setEntity(entity);
    //            HttpResponse resp = client.execute(post);
    //            // 获取回调值
    //            System.out.println("Response:"
    //                    + EntityUtils.toString(resp.getEntity()));
    //            System.out.println("StatusCode:"
    //                    + resp.getStatusLine().getStatusCode());
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //    }


}
